package ru.ssau.berlin.jsf.converters;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import ru.ssau.berlin.ejb.facade.PersonFacade;
import ru.ssau.berlin.ejb.facade.PersonFacadeLocal;
import ru.ssau.berlin.entity.Person;
import ru.ssau.berlin.framework.JNDIHelper;


public class PersonConverter implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        InitialContext ic;
        Person person = null;
        try {
            ic = new InitialContext();
            PersonFacadeLocal facade =
                    (PersonFacadeLocal) ic.lookup(JNDIHelper.getBeanName(PersonFacade.class));
            person = facade.find(Long.parseLong(value));
        } catch (NamingException ex) {
            Logger.getLogger(PersonConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return person;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        Person person = (Person) value;
        return person.getId().toString();
    }

}
